<?php

namespace Gql\Contracts;

use Illuminate\Contracts\Support\Arrayable;

abstract class DataAbstract implements \ArrayAccess, Arrayable,\JsonSerializable
{
    protected $data = [];

    public function __construct($data=[])
    {
        if(is_array($data)||$data instanceof \ArrayAccess || is_object($data)){
            $this->data=$data;
        }

    }
    public function __set($offset, $value)
    {
        $this->data[$offset] = $value;
    }

    public function toJson($options = 0)
    {
        return json_encode($this->jsonSerialize(), $options);

    }
    public function jsonSerialize(){
        return $this->toArray();
    }
    public function toArray()
    {
        return $this->data;
    }

    public function offsetExists($offset)
    {
        $data=$this->data;
        if(is_array($data)){
            return isset($data[$offset]);
        }elseif(is_object($data)){
            return isset($data->{$offset});
        }

    }

    public function offsetGet($offset)
    {
        if ($this->offsetExists($offset)) {
            $data=$this->data;
            if(is_array($data)){
                return $data[$offset];
            }elseif(is_object($data)){
                return $data->{$offset};
            }
        }
    }

    public function offsetSet($offset, $value)
    {
        $this->{$offset}=$value;
    }

    public function offsetUnset($offset)
    {
        if ($this->offsetExists($offset)) {
            unset($this->data[$offset]);
        }
    }
}